<!-- src/components/HonorsManagement.vue -->
<template>
  <div class="honors-management">
    <!-- 顶部控制区域 -->
    <div class="page-header">
      <div class="header-actions">
        <div class="search-filter">
          <input
            v-model="searchForm.keyword"
            @input="debounceFetch"
            placeholder="按学员姓名、学位、荣誉名称等搜索"
            class="search-input"
          />
          <select v-model="searchForm.year" @change="fetchHonors" class="filter-select" title="年份筛选">
            <option value="">全部年份</option>
            <option v-for="y in yearOptions" :key="y" :value="y">{{ y }} 年</option>
          </select>
        </div>
        <button class="btn btn-primary" @click="openCreateModal">
          <i class="icon-plus"></i>新增荣誉
        </button>
      </div>
    </div>

    <!-- 力量卡（简单统计，可按需扩展） -->
    <div class="stats-cards" v-if="total > 0">
      <div class="stat-card">
        <div class="stat-icon" style="background:#4F46E5"><i class="icon-award"></i></div>
        <div class="stat-content">
          <div class="stat-number">{{ total }}</div>
          <div class="stat-label">荣誉总数</div>
        </div>
      </div>
    </div>

    <!-- 荣誉表格 -->
    <div class="table-container" v-if="honors.length > 0">
      <div class="table-header">
        <h3>荣誉列表</h3>
        <div class="table-actions">
          <button @click="exportHonors" class="btn btn-outline">
            <i class="icon-download"></i>导出
          </button>
        </div>
      </div>

      <div class="table-wrapper">
        <table class="data-table">
          <thead>
            <tr>
              <th>荣誉ID</th>
              <th>荣誉名称</th>
              <th>学员姓名</th>
              <th>课程名称</th>
              <th>荣誉类型</th>
              <th>授予日期</th>
<!--              <th>颁发机构</th>-->
<!--              <th>描述</th>-->
              <th>操作</th>

            </tr>
          </thead>
          <tbody>
            <tr v-for="honor in honors" :key="honor.id">
              <td>{{ honor.id }}</td>
              <td>{{ honor.name }}</td>
              <td>{{ honor.student ? honor.student.name : '-' }}</td>
              <td>{{ honor.course ? honor.course.title : '-' }}</td>
              <td>{{ mapHonorTypeToChinese(honor.type) }}</td>
              <td>{{ formatDate(honor.issue_date) }}</td>
<!--              <td>{{ honor.issuer || '-' }}</td>-->
<!--              <td>{{ honor.description || '-' }}</td>-->
              <td>
                <div class="action-buttons">
                  <button @click="editHonor(honor)" class="btn-icon" title="编辑">
                    <i class="icon-edit"></i>编辑
                  </button>
                  <button @click="confirmDelete(honor.id)" class="btn-icon danger" title="删除">
                    <i class="icon-trash"></i>删除
                  </button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <div class="pagination-info">共 {{ total }} 条记录，第 {{ currentPage }}/{{ totalPages }} 页</div>
        <div class="pagination">
          <button @click="changePage(currentPage - 1)" :disabled="currentPage === 1" class="pagination-btn">上一页</button>
          <button
            v-for="p in visiblePages"
            :key="p"
            @click="changePage(p)"
            :class="['pagination-btn', { active: p === currentPage }]"
          >
            {{ p }}
          </button>
          <button @click="changePage(currentPage + 1)" :disabled="currentPage === totalPages" class="pagination-btn">下一页</button>
        </div>
      </div>
    </div>

    <!-- 空态 -->
    <div v-else class="empty-state">
      <p>暂无荣誉数据，点击“新增荣誉”添加记录。</p>
    </div>

    <!-- 新增/编辑荣誉模态框 -->
    <div v-if="showModal" class="modal-overlay" @click="closeModal">
      <div class="modal" @click.stop>
        <div class="modal-header">
          <h3>{{ isEdit ? '编辑荣誉' : '新增荣誉' }}</h3>
          <button class="modal-close" @click="closeModal"><i class="icon-x"></i></button>
        </div>

        <div class="modal-body">
          <form @submit.prevent="saveHonor">
            <div class="form-grid">
              <div class="form-group">
                <label>荣誉名称 *</label>
                <input v-model="form.title" type="text" required placeholder="请输入荣誉名称" />
              </div>

              <!-- 荣誉类型 -->
              <div class="form-group">
                <label>荣誉类型 *</label>
                <select v-model="form.type" required>
                  <option value="">请选择类型</option>
                  <option v-for="type in honorTypeOptions" :key="type.value" :value="type.value">{{ type.label }}</option>
                </select>
              </div>

              <!-- 颁发时间 -->
              <div class="form-group">
                <label>颁发时间 *</label>
                <input v-model="form.date" type="date" required />
              </div>

              <!-- 课程ID -->
              <div class="form-group">
                <label>课程ID</label>
                <input v-model.number="form.course_id" type="number" placeholder="请输入课程ID" />
              </div>
              <!-- 课程名称 (自动显示) -->
              <div class="form-group">
                <label>课程名称</label>
                <input :value="displayCourseName" type="text" readonly :placeholder="courseLoading ? '查询中...' : '根据课程ID自动显示'" />
              </div>

              <!-- 学员ID -->
              <div class="form-group">
                <label>学员ID</label>
                <input v-model.number="form.student_id" type="number" placeholder="请输入学员ID" />
              </div>
              <!-- 学员名称 (自动显示) -->
              <div class="form-group">
                <label>学员名称</label>
                <input :value="displayStudentName" type="text" readonly :placeholder="studentLoading ? '查询中...' : '根据学员ID自动显示'" />
              </div>
            </div>

            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" @click="closeModal">取消</button>
              <button type="submit" class="btn btn-primary" :disabled="saving">
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { honorAPI } from '@/services/api'
const mapHonorTypeToChinese = (type) => {
  if (!type) return '-'; // 处理空值
  // 确保传入的类型与映射的键大小写一致，如果数据库存的是小写 "medal"，这里也用小写键
  // 或者你可以在这里 .toLowerCase() type，以防数据库和枚举大小写不一致
  switch (type) {
    case 'medal':
      return '勋章';
    case 'certificate':
      return '证书';
  }
};
// 状态
const honors = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(15)

const searchForm = reactive({
  keyword: '',
  year: ''
})

const showModal = ref(false)
const isEdit = ref(false)
const currentHonorId = ref(null)

const form = reactive({
  id: null,
  student_id: '',
  student_name: '',
  title: '',
  date: '',
  issuer: '',
  description: ''
})

const loading = ref(false)
const saving = ref(false)

const yearOptions = computed(() => {
  // 只展示最近20年，按需要调整
  const currentYear = new Date().getFullYear()
  const years = []
  for (let y = currentYear; y >= currentYear - 20; y--) years.push(y)
  return years
})

const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

const visiblePages = computed(() => {
  const pages = []
  const maxVisible = 5
  const start = Math.max(1, currentPage.value - Math.floor(maxVisible / 2))
  const end = Math.min(totalPages.value, start + maxVisible - 1)
  for (let i = start; i <= end; i++) pages.push(i)
  return pages
})

// 防抖查询
let searchTimer = null
const debounceFetch = () => {
  clearTimeout(searchTimer)
  searchTimer = setTimeout(() => {
    fetchHonors()
  }, 300)
}

// API 调用
const fetchHonors = async () => {
  loading.value = true
  try {
    const params = {
      skip: (currentPage.value - 1) * pageSize.value,
      limit: pageSize.value,
      keyword: searchForm.keyword || undefined,
      year: searchForm.year || undefined
    }

    // 删除 undefined
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) delete params[key]
      if (params[key] === '') delete params[key]
    })

    const res = await honorAPI.getHonors(params)
    honors.value = res.items || []
    total.value = res.total ?? 0
  } catch (e) {
    console.error('获取荣誉失败', e)
  } finally {
    loading.value = false
  }
}

const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
  fetchHonors()
}

const openCreateModal = () => {
  Object.assign(form, { id: null, student_id: '', student_name: '', title: '', date: '', issuer: '', description: '' })
  showModal.value = true
  isEdit.value = false
  currentHonorId.value = null
}

const editHonor = (honor) => {
  Object.assign(form, {
    id: honor.id,
    student_id: honor.student_id,
    student_name: honor.student_name,
    title: honor.title,
    date: honor.date ? honor.date.substring(0, 10) : '',
    issuer: honor.issuer,
    description: honor.description
  })
  currentHonorId.value = honor.id
  showModal.value = true
  isEdit.value = true
}

const saveHonor = async () => {
  saving.value = true
  try {
    const payload = {
      student_id: form.student_id,
      student_name: form.student_name,
      title: form.title,
      date: form.date,
      issuer: form.issuer,
      description: form.description
    }

    if (isEdit.value && currentHonorId.value) {
      await honorAPI.updateHonor(currentHonorId.value, payload)
    } else {
      await honorAPI.createHonor(payload)
    }

    closeModal()
    fetchHonors()
  } catch (e) {
    console.error('保存荣誉失败', e)
  } finally {
    saving.value = false
  }
}

const confirmDelete = async (id) => {
  if (!confirm('确定要删除该荣誉吗？')) return
  try {
    await honorAPI.deleteHonor(id)
    fetchHonors()
  } catch (e) {
    console.error('删除荣誉失败', e)
  }
}

const closeModal = () => {
  showModal.value = false
  isEdit.value = false
  currentHonorId.value = null
  Object.assign(form, { id: null, student_id: '', student_name: '', title: '', date: '', issuer: '', description: '' })
}

const exportHonors = () => {
  // 简单示例：触发后端导出或在前端下载 CSV，按实际后端能力实现
  console.log('导出荣誉数据')
}

const formatDate = (d) => {
  if (!d) return '-'
  const date = new Date(d)
  if (Number.isNaN(date.getTime())) return d
  return date.toLocaleDateString('zh-CN')
}

// 初始加载
onMounted(() => {
  fetchHonors()
})
</script>

<style scoped>
.honors-management {
  padding: 20px;
}
.page-header {
  margin-bottom: 12px;
}
.header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 12px;
}
.search-filter {
  display: flex;
  gap: 12px;
  align-items: center;
}
.search-input {
  width: 320px;
  padding: 8px 12px;
  border: 1px solid #D1D5DB;
  border-radius: 6px;
}
.filter-select {
  padding: 8px 12px;
  border-radius: 6px;
  border: 1px solid #D1D5DB;
}
.btn {
  padding: 8px 14px;
  border-radius: 6px;
  border: none;
  cursor: pointer;
}
.btn-primary {
  background: #4F46E5;
  color: white;
}
.btn-outline {
  background: white;
  border: 1px solid #4F46E5;
  color: #4F46E5;
}
.btn-secondary {
  background: #F3F4F6;
  color: #374151;
}
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin: 16px 0 8px;
}
.stat-card {
  background: white;
  padding: 14px;
  border-radius: 8px;
  display: flex; align-items: center; gap: 12px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.stat-icon {
  width: 44px; height: 44px; border-radius: 8px;
  display: flex; align-items: center; justify-content: center; color: white;
}
.stat-content .stat-number {
  font-size: 18px; font-weight: 600;
}
.table-container {
  background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-top: 14px;
}
.table-header {
  padding: 14px 16px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center;
}
.table-wrapper {
  overflow-x: auto;
}
.data-table {
  width: 100%; border-collapse: collapse;
}
.data-table th, .data-table td {
  padding: 12px; border-bottom: 1px solid #E5E7EB; text-align: left;
}
.data-table th {
  background: #F9FAFB; font-weight: 600;
}
.avatar-small {
  width: 26px; height: 26px; border-radius: 50%; object-fit: cover;
}
.status-badge {
  padding: 4px 8px; border-radius: 999px; font-size: 12px;
  background: #F3F4F6;
}
.action-buttons {
  display: flex; gap: 6px;
}
.btn-icon {
border-radius: 6px;
border: none;
background: #F3F4F6;
color: #6B7280; /* 图标和文字的颜色 */
display: inline-flex; /* 保持 flex，让图标和文字并排 */
align-items: center; /* 垂直居中对齐 */
padding: 6px 10px; /* <--- 添加内边距，让按钮有空间 */
gap: 4px; /* <--- 添加图标与文字之间的间距 */
justify-content: flex-start; /* <--- 让内容左对齐，而不是完全居中 */
cursor: pointer;
}

.btn-icon:hover {
background: #E5E7EB;
/* color: #374151; /* 如果希望悬停时图标颜色也变深，可以添加此行 */
}

.pagination-wrapper {
  padding: 12px 16px; display: flex; justify-content: space-between; align-items: center;
  border-top: 1px solid #E5E7EB;
}
.pagination-btn {
  padding: 6px 10px; border: 1px solid #D1D5DB; border-radius: 6px; background: white;
  cursor: pointer;
}
.pagination-btn.active {
  background: #4F46E5; color: white; border-color: #4F46E5;
}
.modal-overlay {
  position: fixed; left:0; top:0; right:0; bottom:0;
  background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center;
  z-index: 1000;
}
.modal {
  background: white; border-radius: 8px; width: 90%; max-width: 600px; max-height: 90vh; overflow: auto;
}
.modal-header {
  padding: 14px 16px; border-bottom: 1px solid #E5E7EB; display: flex; justify-content: space-between; align-items: center;
}
.modal-body { padding: 16px; }
.modal-footer {
  display: flex; justify-content: flex-end; gap: 10px; padding: 12px 16px; border-top: 1px solid #E5E7EB;
}
.form-grid {
  display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px;
}
.form-group { display: flex; flex-direction: column; gap: 6px; }
.form-group label { font-size: 13px; color: #374151; }
.form-group input, .form-group textarea {
  padding: 8px 10px; border: 1px solid #D1D5DB; border-radius: 6px; font-size: 14px;
}
.form-group textarea { resize: vertical; min-height: 80px; }
@media (max-width: 600px) {
  .form-grid { grid-template-columns: 1fr; }
}
.empty-state {
  padding: 40px 0; text-align: center; color: #6B7280;
}
</style>
